package com.httpapi;


import android.util.Log;

import com.httpapi.apiservice.OnHttpApiListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.ResponseBody;

/**
 * 下载文件服务
 */
public class FileDownloadRun implements Runnable{
    private retrofit2.Response<ResponseBody> mResponseBody;
    private OnHttpApiListener mDownloadApkListener;
    private String fileNameS;
    private String fileDir;
    private int  tag;
    public FileDownloadRun(int  tag,String fileDir,String fileName , retrofit2.Response<ResponseBody> responseBody,
                           final OnHttpApiListener downloadApkListener){
        Log.d("down","sFileDownloadRun");
        mResponseBody = responseBody;
        fileNameS = fileName;
        mDownloadApkListener = downloadApkListener;
        this.tag = tag;
        this.fileDir = fileDir;
    }

    @Override
    public void run() {
        writeResponseBodyToDisk(tag,fileDir,fileNameS,mResponseBody.body(),mDownloadApkListener);
    }

    /**
     *
     * @param body
     * @param downloadListener
     * @return
     */
    private boolean writeResponseBodyToDisk(int tag,String fileDir,String fileName ,ResponseBody body,final OnHttpApiListener downloadListener) {

        try {
            // 改成自己需要的存储位置
            Log.d("down","writeResponseBodyToDisk");
            File file = new File(fileDir+fileName + ".apk");
            Log.d("down","writeResponseBodyToDisk-->"+file.getPath());
//            LogUtils.e("writeResponseBodyToDisk() file="+file.getPath());
            if (file.exists()) {
                file.delete();
            }
            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[4096];

                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(file);

                int i=0;
                while (true) {
                    int read = inputStream.read(fileReader);
                    if (read == -1) {
                        break;
                    }
                    outputStream.write(fileReader, 0, read);
                    fileSizeDownloaded += read;
                    //计算当前下载百分比，并经由回调传出
                    if (downloadListener!=null){
                        float l = ((float)fileSizeDownloaded) / ((float)fileSize);
                        int pro = (int) (100D * l);
                        Log.d("down","writeResponseBodyToDisk-->"+pro);
                        if(i != pro){
                            //降低回调次数，避免主线程被下载消息阻塞
                            //LogUtils.d(pro+"---");
                            i=pro;
                            downloadListener.onDownLoadProgress(i);
                        }
                    }
                    // LogUtils.d( i+":file download: " + fileSizeDownloaded + " of " + fileSize);
                }
                if (downloadListener!=null)
                    downloadListener.onSuccess(tag,file.getPath());
                outputStream.flush();

                return true;
            } catch (IOException e) {
                Log.d("down","1-->"+e);
                if (downloadListener!=null)
                    downloadListener.onFailure(tag,""+e.getMessage(),0);
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            Log.d("down","2-->"+e);
            return false;
        }
    }
}